#include<vector>
#include<algorithm>
using namespace std;
class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        sort(nums.begin(), nums.end());
        bool flag = false;
        int res = target;
        for (int i = 0; i < nums.size(); ++i) {
            int left = i + 1;
            int right = nums.size() - 1;
            while (left < right) {
                int tmp = nums[i] + nums[left] + nums[right];
                if (tmp == target) return target;
                if (tmp > target)
                    --right;
                else
                    ++left;
                if (!flag || abs(res - target) > abs(tmp - target)) {
                    flag = true;
                    res = tmp;
                }
            }
        }
        return res;
    }
};